<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-form-item label="所属院区" prop="campusName">
        <el-select
            v-model="queryParams.campusName"
            placeholder="请输入所属院区"
            clearable
            filterable
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in campusName"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="handleQuery">
        搜索
      </el-button>
      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
        新增院区
      </el-button>
    </div>

    <!-- 院区列表 -->
    <el-table
        v-loading="loading"
        :data="campusList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >RuoYi-Vue-master
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="指南ID" width="80" align="center"/>
      <el-table-column prop="campusName" label="院区" align="center" />
      <el-table-column prop="address" label="地址" align="center" />

      <!-- 联系电话展示 -->
      <el-table-column label="联系电话" align="center">
        <template #default="scope">
          <div v-if="scope.row.contacts && scope.row.contacts.length" >
            <div v-for="(contact, index) in scope.row.contacts" :key="index">
              {{ contact.phoneNumber }}
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column prop="busInfo" label="公交" align="center" />

      <!-- 院内导航展示 -->
      <el-table-column label="院内导航" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.navigations!=null && scope.row.navigations.length!=0">
            <el-popover
                placement="top-start"
                title="院内导航详情"
                width="300"
                trigger="hover"
            >
              <template #reference>
                <el-tag type="success" style="cursor: pointer">
                  {{ scope.row.navigations.length }} 条导航信息
                </el-tag>
              </template>
              <div v-for="(nav, index) in scope.row.navigations" :key="index" style="margin-bottom: 8px">
                  <div><strong>楼层:</strong> {{ nav.floor }}</div>
                  <div><strong>索引:</strong> {{ nav.floorIndex }}</div>
              </div>
            </el-popover>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>


      <el-table-column
          prop="operationTime"
          label="操作时间"
          align="center"
          width="180"
      >
        <template #default="scope">
          {{ formatTime(scope.row.operationTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="700px"
        @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="width: 100%">
        <!-- 院区名称 -->
        <el-form-item label="院区名称" prop="campusName">
          <el-input v-model="form.campusName" placeholder="请输入院区名称" />
        </el-form-item>
        <!-- 联系电话（支持新增多个） -->
        <el-form-item label="联系电话" prop="contacts">
          <div v-for="(contact, index) in form.contacts" :key="index" class="contact-item">
            <el-input v-model="contact.phoneNumber" placeholder="请输入联系电话" style="width: 240px; margin-right: 10px"/>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="handleRemoveContact(index)">删除</el-button>
          </div>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddContact" style="margin-left: 10px;margin-top: 3rpx">
            新增联系电话
          </el-button>
        </el-form-item>

        <!-- 公交信息 -->
        <el-form-item label="公交" prop="busInfo">
          <el-input v-model="form.busInfo" placeholder="请输入公交信息" />
        </el-form-item>

        <!-- 院区地址 -->
        <el-form-item label="院区地址" prop="address">
          <el-cascader
              v-model="form.address"
              :options="addressOptions"
              placeholder="请选择地区"
              style="width: 100%"
          />
        </el-form-item>

        <!-- 院内导航（支持新增多个楼层） -->
        <el-form-item label="院内导航" prop="navigations">
          <div
              v-for="(navigation, index) in form.navigations"
              :key="index"
              class="navigation-item"
              style="display: flex; align-items: center; margin-bottom: 10px"
          >
            <el-form-item
                :prop="`navigations.${index}.floor`"
                :rules="{ required: true, message: '楼层不能为空', trigger: 'blur' }"
                style="margin-right: 10px; margin-bottom: 0"
            >
              <el-input
                  v-model="navigation.floor"
                  placeholder="楼层（如：1楼）"
                  style="width: 120px"
              />
            </el-form-item>

            <el-form-item
                :prop="`navigations.${index}.floorIndex`"
                :rules="{ required: true, message: '楼层索引不能为空', trigger: 'blur' }"
                style="flex: 1; margin-right: 10px; margin-bottom: 0"
            >
              <el-input
                  v-model="navigation.floorIndex"
                  placeholder="楼层索引（如：总服务台）"
              />
            </el-form-item>

            <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="handleRemoveNavigation(index)"
            >删除</el-button>
          </div>
          <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAddNavigation"
          >新增楼层导航
          </el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {getHospitalCampusName, delDepartmentsByCampusId, addDepartments} from '@/api/system/departments'
import { listCampus, getCampus, saveCampus, updateCampus, deleteCampus } from '@/api/system/hospitalCampus'
import { isEqual } from 'lodash'

// 状态与变量
const loading = ref(false)
const campusList = ref([]) // 使用 ref([]) 确保响应式
const total = ref(0)
const campusName = ref([])
const queryParams = reactive({
  pageNum: 1,
  pageSize: 50,
  campusName: '' // 搜索关键词（院区名称）
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
let form = reactive({
  id: null,
  campusName: '',
  contacts: [{ phoneNumber: '' }], // 初始一个联系电话
  busInfo: '',
  address: [], // 级联选择的地区
  navigations: [],// 院内导航列表
  operationTime: ''
})

// 表单校验规则
const rules = {
  campusName: [{ required: true, message: '请输入院区名称', trigger: "blur" }],
  address: [{ required: true, message: '请选择院区地址', trigger: 'blur' }],
  contacts: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
}

// 地区级联数据
const addressOptions = ref([])

onMounted(() => {
  getCampusList()
  loadAddressOptions()
})

// 加载地区数据
const loadAddressOptions = async () => {
  try {
    addressOptions.value = await getAddressOptions()
  } catch (error) {
    ElMessage.error('加载地区数据失败')
  }
}

//获取院区名称列表
getHospitalCampusName().then(response => {
  for(let i = 0;i < response.length; i++){
    campusName.value.push(response[i].campusName)
  }
})

// 在获取院区列表方法中处理导航数据
const getCampusList = async () => {
  loading.value = true
  try {
    const response = await listCampus(queryParams)
    if (response.data && response.data.list) {
      //处理PageHelper返回的分页数据
      campusList.value = response.data.list
      total.value = response.data.total
    } else if (Array.isArray(response.data)){
      //处理未分页的数据
      campusList.value = response.data
      total.value = response.data.length
    }else{
      ElMessage.error('获取数据失败: 格式错误')
    }
  } catch (error) {
    ElMessage.error('获取院区列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getCampusList()
}

// 分页 - 每页条数改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getCampusList()
}

// 分页 - 当前页改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getCampusList()
}

// 多选
const handleSelectionChange = (val) => {
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.campusName = ''  // 清空院区名称搜索条件
  queryParams.pageNum = 1      // 重置为第一页
  getCampusList()             // 重新加载数据
}

// 新增院区
const handleAdd = () => {
  dialogTitle.value = '新增院区'
  resetForm()
  dialogVisible.value = true
}

// 编辑院区 - 获取详情
const handleUpdate = async (row) => {
  dialogTitle.value = '修改院区'
  resetForm()  // 先重置表单
  try {
    const res = await getCampus(row.id)
    // 使用 Object.assign 避免直接赋值
    Object.assign(form, {
      ...res.data,
      contacts: res.data.contacts || [{ phoneNumber: '' }],
      navigations: res.data.navigations || [{}],
      address: res.data.address ? res.data.address.split('/') : []
    })
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取院区详情失败: ' + error.message)
  }
}


// 删除院区
const handleDelete = async (id) => {
  try {
    await deleteCampus(id)
    ElMessage.success('删除成功')
    await getCampusList()
    await delDepartmentsByCampusId(id)
  } catch (error) {
    ElMessage.error('删除失败，请重试')
  }
}

// 提交表单时处理导航数据
const handleSubmit = async () => {
  try {
    // 过滤空导航项
    const validNavigations = form.navigations.filter(nav =>
        nav.floor && nav.floor.trim() !== '' &&
        nav.floorIndex && nav.floorIndex.trim() !== ''
    )

    // 确保至少有一个导航项
    if (validNavigations.length === 0) {
      ElMessage.warning('请至少添加一条有效的院内导航信息')
      return
    }

    const addressString = Array.isArray(form.address) ? form.address.join('/') : form.address;
    const payload = {
      ...form,
      address: addressString,
      contacts: form.contacts.filter(c => c.phoneNumber.trim() !== ''),
      navigations: validNavigations, // 使用过滤后的导航数据
      operationTime: new Date().getTime() //添加当前时间戳
    }
    console.log(payload)
    if (form.id) {
      console.log((await getCampus(form.id)).data.navigations)
      console.log(payload.navigations)
      if(!isEqual((await getCampus(form.id)).data.navigations, payload.navigations)){
        await updateCampus(payload)
        let b={}
        await delDepartmentsByCampusId(payload.id)
        for(var i = 0; i < payload.navigations.length; i++){
          for(var j = 0; j < payload.navigations[i].floorIndex.split(',').length; j++){
            let b={
              location:payload.navigations[i].floor,
              departmentName:payload.navigations[i].floorIndex.split( ",")[j],
              hospitalArea:payload.campusName,
              delFlag:1,
              campusId: payload.id
            }
            addDepartments(b)
          }
        }
        ElMessage.success('修改成功')
      }else {
        await updateCampus(payload)
        ElMessage.success('修改成功')
      }
    } else {
      await saveCampus(payload)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getCampusList()
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

// 关闭弹窗重置表单
const handleDialogClose = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    campusName: '',
    contacts: [{ phoneNumber: '' }],
    busInfo: '',
    address: [],
    navigations: [{}],
    operationTime: ''
  })
}

// 联系电话操作
const handleAddContact = () => {
  form.contacts.push({ phoneNumber: '' })
}

const handleRemoveContact = (index) => {
  if (form.contacts.length > 1) {
    form.contacts.splice(index, 1)
  } else {
    form.contacts[0].phoneNumber = ''
  }
}

// 新增楼层导航
const handleAddNavigation = () => {
  form.navigations.push({})
}

// 删除楼层导航
const handleRemoveNavigation = (index) => {
  if (form.navigations.length > 1) {
    form.navigations.splice(index, 1)
  } else {
    form.navigations[0] = {}
  }
}

// 获取地址级联数据
function getAddressOptions() {
  return new Promise((resolve) => {
    // 模拟数据，实际替换为接口请求
    const options = [
      {
        label: '北京市',
        value: '北京市',
        children: [
          {
            label: '大兴区',
            value: '大兴区',
            children: [
              { label: '黄村镇', value: '黄村镇' },
              { label: '其他镇', value: '其他镇' }
            ]
          }
        ]
      },
      {
        label: '上海市',
        value: '上海市',
        children: [
          {
            label: '浦东新区',
            value: '浦东新区',
            children: [
              { label: 'xx街道', value: 'xx街道' }
            ]
          }
        ]
      }
    ]
    resolve(options)
  })
}

//操作时间
function formatTime(time, format = '{y}-{m}-{d} {h}:{i}:{s}') {
  if (!time) return '暂无时间'
  try {
    const date = new Date(time)
    if (isNaN(date.getTime())) return '无效时间'

    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds()
    }
    return format.replace(/{(y|m|d|h|i|s)}/g, (_, key) => {
      let val = formatObj[key]
      if (key !== 'y') {
        val = val.toString().padStart(2, '0')
      }
      return val
    })
  } catch (e) {
    return '时间格式错误'
  }
}
</script>

<style scoped>
/* 添加导航项样式 */
.navigation-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #f5f7fa;
}
</style>